﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;
using Tiens.NotificationHub.Constant;
using Tiens.NotificationHub.Core.Extensions;
using Tiens.NotificationHub.Core.Utils;

namespace Tiens.NotificationHub.Core.Services
{
    public class InMemoryTokenManager
    {
        private readonly IMemoryCache _memoryCache;
        private readonly IServiceProvider _services;

        public InMemoryTokenManager(IMemoryCache memoryCache, IServiceProvider services)
        {
            _memoryCache = memoryCache;
            _services = services;
        }

        public async Task<string> UserIdAsync(string token, CancellationToken cancellationToken =default)
            => await GetCachedUserId(token, cancellationToken);

        private async Task<string> GetCachedUserId(string token,CancellationToken cancellationToken) =>
            await _memoryCache.GetOrCreateAsync(token.ToTokenCacheKey(),  e =>
            {
                e.SetSlidingExpiration(TimeSpan.FromMinutes(30));

                using var serviceScope = _services.CreateScope();
                var provider = serviceScope.ServiceProvider;

                var decryptor = provider.GetRequiredService<CBCDecryptor>();

                return Task.FromResult(decryptor.DecryptToUserId(token));
            });

    }

}
